import { Component, ViewChild, Injector, Output, EventEmitter, ViewEncapsulation, ElementRef } from '@angular/core';
import { ModalDirective, DatepickerConfig } from 'ngx-bootstrap';
import {
  ClassServiceProxy,
  AjaxResponseOfListOfNullableOfInt32,
  ClassUploadInputDto
} from '@shared/service-proxies/service-proxies';
import { AppComponentBase } from '@shared/app-component-base';
import { AppConsts } from '@shared/AppConsts';
import { WebUploaderComponent, File, FileStatus, Options, OptionsAccept } from 'ngx-webuploader';
import * as moment from 'moment';
moment.locale("zh-cn");
@Component({
  moduleId: module.id,
  selector: 'micro-class-add',
  templateUrl: 'micro-class-add.component.html',
  styleUrls: ['micro-class-add.component.scss'],
  encapsulation: ViewEncapsulation.None,
  providers: [DatepickerConfig]
})
export class MicroClassAddComponent extends AppComponentBase {
  @ViewChild('createClassModal')
  modal: ModalDirective;
  @Output()
  modalSave: EventEmitter<any> = new EventEmitter<any>();

  active: boolean = false;
  saving: boolean = false;
  apiBaseUrl = AppConsts.remoteServiceBaseUrl + '/file/download/';
  class: ClassUploadInputDto = null;
  audioOptions: Options = {
    server: AppConsts.remoteServiceBaseUrl + '/file/upload',
    // 自动上传。
    auto: true,
    // 选择文件的按钮。可选。
    // 内部根据当前运行是创建，可能是input元素，也可能是flash.
    pick: { id: '#audioFilePicker', multiple: false },
    formData: { 'associateType': 'MicroClassVideo', 'objectId': '' },
    // 只允许选择文件，可选。
    accept: <OptionsAccept>{
      title: 'Audio',
      mimeTypes: 'audio/*'
    }
  };
  imgOptions: Options = {
    server: AppConsts.remoteServiceBaseUrl + '/file/upload',
    // 自动上传。
    auto: true,
    // 选择文件的按钮。可选。
    // 内部根据当前运行是创建，可能是input元素，也可能是flash.
    pick: { id: '#imgFilePicker', multiple: false },
    formData: { 'associateType': 'MicroClassVideoThumbnail', 'objectId': '' },
    // 只允许选择文件，可选。
    accept: <OptionsAccept>{
      title: 'Images',
      extensions: 'gif,jpg,jpeg,bmp,png',
      mimeTypes: 'image/*'
    }
  };
  constructor(
    injector: Injector,
    private _classService: ClassServiceProxy
  ) {
    super(injector);
  }

  onImgReady(uploader: WebUploaderComponent) {
    const $list = $('#imgFileList');
    // 优化retina, 在retina下这个值是2
    const ratio = window.devicePixelRatio || 1;
    // 当有文件添加进来的时候
    uploader.Instance.on('fileQueued',
      file => {
      });
    // 文件上传过程中创建进度条实时显示。
    uploader.Instance.on('uploadProgress',
      (file, percentage) => {
        const $li = $('#' + file.id);
        let $percent = $li.find('.progress span');

        // 避免重复创建
        if (!$percent.length) {
          $percent = $('<p class="progress"><span></span></p>')
            .appendTo($li)
            .find('span');
        }

        $percent.css('width', percentage * 100 + '%');
      });

    // 文件上传成功，给item添加成功class, 用样式标记上传成功。
    uploader.Instance.on('uploadSuccess',
      (file, result) => {
        const obj = new AjaxResponseOfListOfNullableOfInt32();
        obj.init(result);
        if (this.class.thumbnailAttachmentIds.length) {
          this.class.thumbnailDelAttachmentIds.push(this.class.thumbnailAttachmentIds[0]);
        }
        obj.result.forEach(element => {
          this.class.thumbnailAttachmentIds = [element];
        });

        $('#' + file.id).addClass('upload-state-done');
      });

    // 文件上传失败，现实上传出错。
    uploader.Instance.on('uploadError',
      file => {
        const $li = $('#' + file.id);
        let $error = $li.find('div.error');
        // 避免重复创建
        if (!$error.length) {
          $error = $('<div class="error"></div>').appendTo($li);
        }
        $error.text('上传失败');
      });
    // 完成上传完了，成功或者失败，先删除进度条。
    uploader.Instance.on('uploadComplete',
      file => {
        $('#' + file.id).find('.progress').remove();
      });
  }

  onImgDestroy() {
    console.log('onDestroy');
  }

  onAudioReady(uploader: WebUploaderComponent) {
    const $list = $('#audioFileList');
    // 优化retina, 在retina下这个值是2
    const ratio = window.devicePixelRatio || 1;
    // 当有文件添加进来的时候
    uploader.Instance.on('fileQueued',
      file => {
      });
    // 文件上传过程中创建进度条实时显示。
    uploader.Instance.on('uploadProgress',
      (file, percentage) => {
        const $li = $('#' + file.id);
        let $percent = $li.find('.progress span');

        // 避免重复创建
        if (!$percent.length) {
          $percent = $('<p class="progress"><span></span></p>')
            .appendTo($li)
            .find('span');
        }

        $percent.css('width', percentage * 100 + '%');
      });

    // 文件上传成功，给item添加成功class, 用样式标记上传成功。
    uploader.Instance.on('uploadSuccess',
      (file, result) => {
        const obj = new AjaxResponseOfListOfNullableOfInt32();
        obj.init(result);
        if (this.class.attachmentIds.length) {
          this.class.delAttachmentIds.push(this.class.attachmentIds[0]);
        }
        obj.result.forEach(element => {
          this.class.attachmentIds = [element];
        });

        $('#' + file.id).addClass('upload-state-done');
      });

    // 文件上传失败，现实上传出错。
    uploader.Instance.on('uploadError',
      file => {
        const $li = $('#' + file.id);
        let $error = $li.find('div.error');
        // 避免重复创建
        if (!$error.length) {
          $error = $('<div class="error"></div>').appendTo($li);
        }
        $error.text('上传失败');
      });
    // 完成上传完了，成功或者失败，先删除进度条。
    uploader.Instance.on('uploadComplete',
      file => {
        $('#' + file.id).find('.progress').remove();
      });
  }

  onAudioDestroy() {
    console.log('onDestroy');
  }


  show(groupId: number, classId?: number): void {
    this.active = true;
    if (classId) {
      this.getEditorDto(classId);
    } else {
      this.class = new ClassUploadInputDto();
      this.class.groupId = groupId;
      this.class.attachmentIds = [];
      this.class.delAttachmentIds = [];
      this.class.thumbnailAttachmentIds = [];
      this.class.thumbnailDelAttachmentIds = [];
      this.modal.show();
    }
  }

  getEditorDto(id: number): void {
    this._classService.getClassEditDtoAsync(id).subscribe((result: ClassUploadInputDto) => {
      this.class = result;
      this.modal.show();
    });
  }

  save(): void {
    console.log(arguments);
    this.saving = true;
    this.class.classTime = moment(this.class.classTime);
    this._classService.uploadClassAsync(this.class).finally(() => { this.saving = false; })
      .subscribe(() => {
        this.close();
        this.modalSave.emit(null);
      });
  }

  close(): void {
    this.active = false;
    this.modal.hide();
  }
}
